package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.pay.config.RabbitMQConfig;
import com.changgou.pay.service.WXPaService;
import com.changgou.utill.ConvertUtils;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/wxpay")
@RestController
public class WXPayController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WXPaService wxPaService;

    @GetMapping("/nativePay")
    public Result<Map> nativePay(@RequestParam("orderId") String orderId, @RequestParam("money")Integer money){
        Map map = wxPaService.nativePay(orderId, money);
        return new Result<Map>(true, StatusCode.OK,"",map);
    }

    @RequestMapping("/notify")
    public void notifyLogic(HttpServletRequest request, HttpServletResponse response){
        System.out.println("支付成功回调");
        try {
            //接收微信返回的消息
            //输入流转换为字符串
            ServletInputStream inputStream = request.getInputStream();
            String xml = ConvertUtils.convertToString(inputStream);
            System.out.println(xml);
            //将xml格式转换成字符串格式
            Map<String, String> map = WXPayUtil.xmlToMap(xml);



            //给微信一个结果通知
            response.setContentType("text/xml");
            String data="<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            response.getWriter().write(data);

            //查询订单操作
            if("SUCCESS".equals(map.get("result_code"))){
                //如果订单支付成功,查询订单
                String orderId = map.get("out_trade_no");
                Map queryResult = wxPaService.queryOrder(orderId);
                if("SUCCESS".equals(queryResult.get("result_code"))){
                    //如果查询成功,将订单的消息发送到mq
                    HashMap<String, String> message = new HashMap<>();
                    message.put("transactionId",(String) queryResult.get("transaction_id"));
                    message.put("orderId",(String) queryResult.get("out_trade_no"));
                    rabbitTemplate.convertAndSend("", RabbitMQConfig.ORDER_PAY, JSON.toJSONString(message));

                    rabbitTemplate.convertAndSend("paynotify","",(String)queryResult.get("out_trade_no"));
                }

            }else {
                //如果订单支付不成功,打印错误原因
                System.out.println(map.get("err_code_des"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //基于微信查询订单
    @GetMapping("/query/{orderId}")
    public Result queryOrder(@PathVariable String orderId){
        Map map = wxPaService.queryOrder(orderId);
        return new Result(true,StatusCode.OK,"查询订单成功",map);
    }

    @GetMapping("/close/{orderId}")
    public Result closeOrder(@PathVariable String orderId){
        Map map = wxPaService.closeOrder(orderId);
        return new Result(true,StatusCode.OK,"关闭订单成功",map);
    }
}
